import { NextRequest, NextResponse } from 'next/server';
import { getDeviceParameterDb } from '@/lib/device-parameter-database';

export interface ObjectCategory {
  category_code: string;
  category_name: string;
  specialty: string;
  device_type_count: number;
  classification_codes: string[];
}

// GET /api/object-categories?specialty=配管专业
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const specialty = searchParams.get('specialty');
    
    const db = getDeviceParameterDb();
    
    // 获取设备类型映射
    let mappings;
    if (specialty) {
      mappings = db.getDeviceTypeMappingsBySpecialty(specialty);
    } else {
      mappings = db.getAllDeviceTypeMappings();
    }
    
    // 按对象分类分组
    const categoryMap = new Map<string, {
      category_code: string;
      category_name: string;
      specialty: string;
      classification_codes: string[];
      device_type_count: number;
    }>();
    
    mappings.forEach((mapping) => {
      // 从分类码提取分类代码，例如 "L4-06-01-01-01-000" -> "L4-06"
      const categoryCode = mapping.classification_code.split('-').slice(0, 2).join('-');
      const categoryName = getCategoryName(categoryCode, mapping.classification_name);
      
      if (!categoryMap.has(categoryCode)) {
        categoryMap.set(categoryCode, {
          category_code: categoryCode,
          category_name: categoryName,
          specialty: mapping.specialty,
          classification_codes: [],
          device_type_count: 0
        });
      }
      
      const category = categoryMap.get(categoryCode)!;
      category.classification_codes.push(mapping.classification_code);
      category.device_type_count += 1;
    });
    
    const objectCategories = Array.from(categoryMap.values()).sort((a, b) => 
      a.category_code.localeCompare(b.category_code)
    );
    
    return NextResponse.json({
      success: true,
      data: objectCategories
    });
    
  } catch (error) {
    console.error('获取对象分类失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '获取对象分类失败'
    }, { status: 500 });
  }
}

// 根据分类代码获取分类名称
function getCategoryName(categoryCode: string, firstDeviceName: string): string {
  // 根据实际业务逻辑定义分类名称
  if (categoryCode.startsWith('L4-06')) {
    return '泵类设备';
  } else if (categoryCode.startsWith('L4-07')) {
    return '阀类设备';
  } else if (categoryCode.startsWith('L4-08')) {
    return '容器设备';
  } else if (categoryCode.startsWith('L4-09')) {
    return '换热器设备';
  } else if (categoryCode.startsWith('L4-10')) {
    return '过滤设备';
  } else if (categoryCode.startsWith('L4-11')) {
    return '分离设备';
  } else if (categoryCode.startsWith('L4-12')) {
    return '搅拌设备';
  }
  
  // 如果没有匹配，从第一个设备名称中提取通用部分
  return firstDeviceName.replace(/[0-9#]+.*$/, '').trim() + '类设备';
}